import { defineStore } from 'pinia'
import type { UserInfo } from '../types/user'
import { login as loginApi, register as registerApi } from '../services/authService'

interface UserState {
  userInfo: UserInfo | null
  token: string | null
  isAuthenticated: boolean
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userInfo: null,
    token: localStorage.getItem('token'),
    isAuthenticated: !!localStorage.getItem('token')
  }),

  getters: {
    getUserInfo: (state) => state.userInfo,
    getToken: (state) => state.token,
    isLoggedIn: (state) => state.isAuthenticated
  },

  actions: {
    // 用户登录
    async login(username: string, password: string) {
      try {
        const response: any = await loginApi({ username, password })
        console.log('Login API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { user_id: ..., username: ..., token: ..., expires_at: ... } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success && response.data && response.data.token) {
          const userData = response.data
          this.token = userData.token
          this.userInfo = {
            user_id: userData.user_id,
            username: userData.username,
            email: '', // 登录接口没有返回邮箱，需要通过getUserInfo获取
            created_at: userData.expires_at
          }
          this.isAuthenticated = true
          
          // 保存token到localStorage
          localStorage.setItem('token', userData.token)
          
          return { success: true, message: '登录成功' }
        } else {
          return { success: false, message: response?.message || '登录失败' }
        }
      } catch (error: any) {
        console.error('Error logging in:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 400) {
          return { success: false, message: '用户名或密码错误' }
        } else {
          return { success: false, message: error.message || '登录失败' }
        }
      }
    },

    // 用户注册
    async register(username: string, email: string, password: string) {
      try {
        const response: any = await registerApi({ username, email, password })
        console.log('Register API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { user_id: ..., username: ..., email: ..., created_at: ... } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success && response.data && response.data.user_id) {
          return { success: true, message: response.message || '注册成功' }
        } else {
          return { success: false, message: response?.message || '注册失败' }
        }
      } catch (error: any) {
        console.error('Error registering:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 400) {
          return { success: false, message: '输入数据有误，请检查后重试' }
        } else if (error.response?.status === 409) {
          return { success: false, message: '用户名或邮箱已存在' }
        } else {
          return { success: false, message: error.message || '注册失败' }
        }
      }
    },

    // 退出登录
    logout() {
      this.userInfo = null
      this.token = null
      this.isAuthenticated = false
      
      // 清除localStorage中的token
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    },

    // 设置用户信息
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
    }
  }
})